﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AvalonDock.Layout.Serialization;
using CommunityToolkit.Mvvm.Messaging;
using 多协议通信平台.Models;
using 多协议通信平台.Msg;

namespace 多协议通信平台.Views.Protocal
{
    /// <summary>
    /// FinsView.xaml 的交互逻辑
    /// </summary>
    public partial class FinsView : UserControl
    {
        public FinsView()
        {
            InitializeComponent();
            Loaded += FinsView_Loaded;
        }

        private string _initialLayout;

        private void FinsView_Loaded(object sender, RoutedEventArgs e)
        {
            var serializer = new XmlLayoutSerializer(dockingManager);
            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer);
                _initialLayout = writer.ToString();
            }
        }


        private void ResetLayout(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(_initialLayout))
            {
                var serializer = new XmlLayoutSerializer(dockingManager);
                using (var reader = new StringReader(_initialLayout))
                {
                    serializer.Deserialize(reader); // 恢复到初始状态
                }
            }
        }
        // 节流效果 1000ms 内只能触发一次
        private DateTime _lastTriggerTime = DateTime.MinValue;
        private void DataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (e == null) return;

            // 检查是否滚动到底部
            var scrollViewer = e.OriginalSource as ScrollViewer;
            if (e.VerticalOffset != 0 && e.VerticalOffset == scrollViewer.ScrollableHeight)
            {
                if ((DateTime.Now - _lastTriggerTime).TotalMilliseconds < 1000)
                    return;
                Debug.WriteLine($"触发加载事件,Offset: {e.VerticalOffset},ScrollableHeight: {scrollViewer.ScrollableHeight}");
                WeakReferenceMessenger.Default.Send(new NotifyMessage(null) { MsgType = "load" });
                _lastTriggerTime = DateTime.Now;
            }
        }
    }
}
